<template>
  <div id="article-comments">
    <div
      class="top-comments"
      v-if="comments.pagination.total != 0 && comments.pagination.total != null"
    >
      <div class="show">
        <div v-for="comment in comments.data" :key="comment.id">
          <single-comment :comment="comment" :articleId="props.articleId"></single-comment>
        </div>
      </div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          :size="size"
          :disabled="disabled"
          v-model:page-size="pageSize"
          :background="background"
          layout="prev, pager, next, jumper"
          :total="comments.pagination.total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div v-else>
      <el-empty description="暂无评论"></el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useArticleManageStore } from '@/stores/useArticleManageStore'
import { ComponentSize } from 'element-plus'
import { computed, onBeforeMount, onMounted, ref, watch } from 'vue'
import SingleComment from '@/components/comment/SingleComment.vue'

const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const currentPage = ref(1) //当前在哪一页
const pageSize = ref(10) //每一页展示多少数据
// const total = computed(() => comments.value.total)//一共有多少页

/**
 * 获取文章的评论内容
 */
const props = defineProps({
  articleId: Number,
})
const articleManage = useArticleManageStore()
// const comments = ref({
//   data: [],
//   pagination: { page: currentPage.value, pageSize: pageSize.value, total: 0 },
// })
const comments = computed(() => {
  return (
    articleManage.comments[props.articleId] ?? {
      data: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
    }
  )
})
watch(
  comments,
  (newVal, oldVal) => {
    console.log('评论区发生变化：')
    console.log('新的评论区数据:', newVal)
    console.log('旧的评论区数据:', oldVal)
  },
  { deep: true }, // 深度监听，确保嵌套结构变化也能捕捉到
)
//展示评论的内容
// onBeforeMount(async () => {
//   comments.value = await articleManage.fetchComments(
//     Number(props.articleId),
//     currentPage.value,
//     pageSize.value,
//   )
// })
const fetch = async () => {
  await articleManage.fetchComments(props.articleId, currentPage.value, pageSize.value, true)
}
onMounted(fetch)
watch([currentPage, pageSize], fetch)
// const handleCurrentChange = async (val: number) => {
//   comments.value = await articleManage.fetchComments(Number(props.articleId), val, pageSize.value) //更新评论内容
// }
</script>

<style scoped>
#article-comments {
  width: 100%;
}

.demo-pagination-block {
  margin: 10px auto;
  display: flex;
}

.el-pagination {
  margin: 0px auto;
}
</style>
